package anveshitha.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FileUtils {

	public static ArrayList<File> listFiles(File fSrcDir, String fileExtn, boolean recursive) throws FileNotFoundException {

		validateDirectory(fSrcDir);
		ArrayList<File> fileList = new ArrayList<File>();

		File[] filesAndDirs = fSrcDir.listFiles();
		List<File> filesDirs = Arrays.asList(filesAndDirs);

		for (File file : filesDirs) {

			if (file.exists() && file.canRead() && file.isFile() && file.getAbsolutePath().endsWith(fileExtn))
				fileList.add(file);

			if (!file.isFile() && recursive) {
				//must be a directory
				//recursive call!
				List<File> deeperList = listFiles(file, fileExtn,recursive);
				fileList.addAll(deeperList);
			}

		}

		Collections.sort(fileList);
		return fileList;

	}

	/**
	 * Directory is valid if it exists, does not represent a file, and can be read.
	 */
	static private void validateDirectory(File aDirectory)
			throws FileNotFoundException {
		if (aDirectory == null) {
			throw new IllegalArgumentException("Directory should not be null.");
		}
		if (!aDirectory.exists()) {
			throw new FileNotFoundException("Directory does not exist: "
					+ aDirectory);
		}
		if (!aDirectory.isDirectory()) {
			throw new IllegalArgumentException("Is not a directory: "
					+ aDirectory);
		}
		if (!aDirectory.canRead()) {
			throw new IllegalArgumentException("Directory cannot be read: "
					+ aDirectory);
		}
	}

}
